import Cookies from 'js-cookie'

const TokenKey = 'Admin-Token'

export function getToken() {
  return Cookies.get(TokenKey)
}

export function setToken(token) {
  return Cookies.set(TokenKey, token)
}

export function removeToken() {
  return Cookies.remove(TokenKey)
}

/**
 * @param {String} name cookie名称
 * @param {String} value cookie值
 * @param {Number} expiredays 过期时间，天数
 */
export function setCookie(name, value, expiredays) {
  const exdate = new Date()
  // setDate获取N天后的日期
  exdate.setDate(exdate.getDate() + expiredays) // getDate() 获取当前月份的日 + 过期天数
  document.cookie = name + '=' + encodeURI(value) + ';path=/;expries=' + exdate.toLocaleString()
}
/**
 * 获取cookie值
 * @param {String} name cookie名称
 */
export function getCookie(name) {
  var arr = document.cookie.split(';')
  for (var i = 0; i < arr.length; i++) {
    var arr2 = arr[i].split('=')
    if (arr2[0].trim() === name) {
      return arr2[1]
    }
  }
}
/**
 * 删除绑定cookie值
 * @param {String} name cookie名称
 */
export function clearCookie(name) {
  setCookie(name, '', -1)
}
/**
 * 浏览器是否支持本地cookie
 */
export function isSupportLocalCookie() {
  const { name, value } = { name: 'name', value: 'migze' }
  setCookie(name, value, 1) // 设置cookie
  return getCookie(name).includes(value) // includes 判断数组name中是否含有当前value(返回true or false)
}

const CryptoJS = require('crypto-js') // 引用AES源码js
const key = CryptoJS.enc.Utf8.parse('1234123412ABCDEF') // 十六位十六进制数作为密钥
const iv = CryptoJS.enc.Utf8.parse('ABCDEF1234123412') // 十六位十六进制数作为密钥偏移量

// 加密方法
export function Encrypt(word) {
  const srcs = CryptoJS.enc.Utf8.parse(word)
  const encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 })
  return encrypted.ciphertext.toString().toUpperCase()
}
// 解密方法
export function Decrypt(word) {
  const encryptedHexStr = CryptoJS.enc.Hex.parse(word)
  const srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr)
  const decrypt = CryptoJS.AES.decrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 })
  const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
  return decryptedStr.toString()
}
